package com.study.concurrent.B_ThreadSynchronizedBasic.d_UseConditionsInSynchronizedCodes;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by 赵超 on 2017/3/22.
 * 数据存储类
 * */
public class EventStorage {
    /**
     * 两个属性 缓冲区最大值和存储列表List
     */
    private int maxSize;
    private List<Date> storage;

    /**
     * 通过构造器初始化两个属性的值
     */
    public EventStorage() {
        maxSize = 10;
        storage = new LinkedList<>();
    }

    /**
     * 保存数据到存储列表中
     */
    public synchronized void set() {
        // 判断存储列表是否已满，满了就会使线程挂起
        while (storage.size() == maxSize) {
            try {
                System.out.println(Thread.currentThread().getName() + "调用set方法挂起");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        storage.add(new Date());
        System.out.printf("保存数据，存储列表大小：%d\n", storage.size());
        // 唤醒所有因调用wait()方法而挂起的线程
        notifyAll();
    }

    /**
     * 从存储列表中获取数据
     */
    public synchronized void get() {
        // 判断存储列表是否为空，为空就会使线程挂起
        while (storage.size() == 0) {
            try {
                System.out.println(Thread.currentThread().getName() + "调用get方法挂起");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 调用LinkedList的poll()方法来取回移除（取出）列表中第一个元素  Retrieves and removes the head (first element) of this list.
        System.out.printf("获取数据，存储列表的大小：%d : %s\n", storage.size(), ((LinkedList)storage).poll());
        notifyAll();
    }
}
